package com.freecloud.framework.interceptor;

import cn.hutool.core.util.StrUtil;
import com.freecloud.framework.annotation.CORS;
import com.freecloud.framework.utils.PropertiesUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 跨域请求，增加CORS请求头
 */
@Component
public class CrossDomainInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        CORS annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(CORS.class);
        }else{
            return true;
        }

        if(annotation == null){
            return true;
        }

        //如果有@CORS注解，则增加cors头信息
        String sourceUrl = request.getHeader("Referer");

        if(StrUtil.isNotEmpty (sourceUrl) && PropertiesUtil.checkWhiteURL(sourceUrl)) {
            response.addHeader ("Access-Control-Allow-Origin",request.getHeader("Origin"));
            response.addHeader ("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE");
            //预检请求的间隔时间
            response.addHeader("Access-Control-Max-Age", "3600");
            response.addHeader ("Access-Control-Allow-Headers","x-requested-with,content-type");
            //允许跨域请求携带的请求头
            response.addHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token,Access-Control-Allow-Headers");
            //若要返回cookie、携带seesion等信息则将此项设置我true
            response.addHeader("Access-Control-Allow-Credentials","true");
        }

        return true;
    }
}
